package com.lancoo.answer.view.fragment.correctmistake

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.lancoo.answer.databinding.EvFmtGctReviewBinding
import com.lancoo.answer.model.AnswerConstant
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.bean.ModelAnswerArea
import com.lancoo.answer.model.bean.ModelAnswerInfo
import com.lancoo.answer.model.bean.Ques
import com.lancoo.answer.model.bean.TextInfo
import com.lancoo.answer.util.ExamFontSizeAdjustUtils
import com.lancoo.answer.util.HtmlUtils
import com.lancoo.answer.view.adapter.CorrectMistakesTextAdapter
import com.lancoo.answer.view.base.BaseBindingFragment
import com.lancoo.answer.widget.DrawView

/**
 * Created by wealive on 2021/9/24.
 * 改错题数字化答案查看原题,查看作答
 *不展示解析
 */
class FavoriteCorrectMistakesFragment : BaseBindingFragment<EvFmtGctReviewBinding>() {
    private val textInfoList = mutableListOf<TextInfo>()
    private lateinit var adapter: CorrectMistakesTextAdapter
    private val answerInfoList = mutableListOf<ModelAnswerInfo>()
    private var GenreType = 0
    private var GenreID = 0
    private val answerArea = mutableListOf<ModelAnswerArea>()
    private lateinit var ques: Ques
    private var typeIndex = 0
    private var quesIndex = 0
    private var defaultLoadIndex = 0

    companion object {
        fun loadFragment(typeIndex: Int, quesIndex: Int, defaultLoadIndex: Int): Fragment {
            val mBundle = Bundle()
            mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, typeIndex)
            mBundle.putInt(AnswerConstant.KEY_QUESINDEX, quesIndex)
            mBundle.putInt("loadQuesIndex", defaultLoadIndex)
            val favoriteCorrectMistakesFragment = FavoriteCorrectMistakesFragment()
            favoriteCorrectMistakesFragment.arguments = mBundle
            return favoriteCorrectMistakesFragment
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (ques.QuesIndexText != null && ques.QuesIndexText!!.isNotEmpty()) {
            binding.tvLeader.text = HtmlUtils.setText(ques.QuesIndexText!!)
            binding.tvLeader.visibility = View.VISIBLE
        } else {
            binding.tvLeader.visibility = View.INVISIBLE
        }
        val itemList = ques.ChildList!![0].ItemList!!
        val sbAnalysis = StringBuffer()
        for (i in itemList.indices) {
            sbAnalysis.append("${itemList[i].ItemSortIndex}.${itemList[i].ItemAnalysis.let { if (it!!.isEmpty()) "...略" else it }}\n")
        }
        adapter = CorrectMistakesTextAdapter(0, requireContext(), textInfoList, answerArea)
        binding.fl.setAdapter(adapter)
        val subChildItemBeanXList =
            ques.ModelAnswerInfoList!!
        if (ques.ChildList!![0].ItemList!!.size == 1) {
            binding.tvIndex.text = "${ques.ChildList!![0].ItemList!![0].ItemSortIndex}."
        } else if (answerArea.size > 1) {
            for (i in textInfoList.indices) {
                drawArea(i)
            }
        } else if (ques.ChildList!![0].ItemList!!.size == 1) {
            binding.tvIndex.text = "${ques.ChildList!![0].ItemList!![0].ItemSortIndex}."
        }
        try {
            for (i in subChildItemBeanXList.indices) {
                val itemAnswerList =
                    subChildItemBeanXList[i].Answer!!.split("$|")
                val itemPosition = itemAnswerList[0].split("*|")[0]
                val itemType = itemAnswerList[0].split("*|")[1].toInt()
                val itemAnswer = itemAnswerList[0].split("*|")[2]
                if (itemPosition.contains("-")) {
                    val startPosition = itemPosition.split("-")[0].toInt()
                    val endPosition = itemPosition.split("-")[1].toInt()
                    val viewList = mutableListOf<View>()
                    textInfoList.forEachIndexed { index, textInfo ->
                        if (textInfo.Index in startPosition..endPosition) {
                            viewList.add(binding.fl.getChildAt(index))
                        }
                    }
                    drawAnswer(
                        itemType,
                        "本区域无错",
                        startPosition,
                        binding.fl.getChildAt(startPosition),
                        viewList
                    )
                } else {
                    drawAnswer(
                        itemType,
                        if (itemType == 4) "无错" else itemAnswer,
                        getTextPosition(itemPosition.toInt()),
                        binding.fl.getChildAt(getTextPosition(itemPosition.toInt())),
                        mutableListOf(binding.fl.getChildAt(getTextPosition(itemPosition.toInt())))
                    )
                }
            }
        } catch (e: Exception) {

        } finally {

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initAnswerData()
    }

    private fun initAnswerData() {
        if (ConstantBean.constantExamBean == null) {
            return
        }
        val kindBeanList = ConstantBean.constantExamBean!!.TypeList
        typeIndex = requireArguments().getInt(AnswerConstant.KEY_TYPEINDEX)
        quesIndex = requireArguments().getInt(AnswerConstant.KEY_QUESINDEX)
        defaultLoadIndex = requireArguments().getInt("loadQuesIndex")
        ques = kindBeanList!![typeIndex].QuesList!![quesIndex]
        GenreType = ques.GenreType!!.toInt()
        GenreID = ques.GenreID!!.toInt()
        val answerAreaList = ques.ModelAnswerAreaList!!
        for (i in answerAreaList.indices) {
            val area = answerAreaList[i]
            answerArea.add(area)
        }
        textInfoList.addAll(
            ques.ModelTextInfoList!!
        )
        answerInfoList.addAll(
            ques.ModelAnswerInfoList!!
        )
    }

    /*绘制编号*/
    private fun drawArea(position: Int) {
        answerArea.forEachIndexed { index, it ->
            if (it.AnswerArea!!.split("-")[0].toInt() == textInfoList[position].Index) {
                val child = binding.fl.getChildAt(position)
                val tvIndex =
                    DrawView(
                        false,
                        false,
                        child,
                        ques.ChildList!![0].ItemList!![if (ques.ChildList!![0].ItemList!!.size > 1) index else 0].ItemSortIndex!!,
                        "",
                        -1,
                        1,
                        requireContext()
                    )
                binding.flLayout.addView(tvIndex)
            }
        }
    }

    /*绘制保存的作答*/
    @SuppressLint("UseCompatLoadingForDrawables")
    private fun drawAnswer(
        type: Int,
        answer: String,
        position: Int,
        child: View,
        list: MutableList<View>
    ) {
        val isFirst = isFirstPosition(position)
        when (type) {
            0, 1, 2, 3 -> {
                val answerView =
                    DrawView(false, isFirst, child, answer, "", type, 0, requireContext())
                binding.flLayout.addView(answerView)
            }
            4 -> {
                val answerView =
                    DrawView(false, isFirst, answer, "", list, type, 0, requireContext())
                binding.flLayout.addView(answerView)
            }
        }
    }

    /*是否是区域第一个*/
    private fun isFirstPosition(position: Int): Boolean {
        var isFirst = false
        if (answerArea.size == 10) {
            answerArea.forEach {
                if (textInfoList[position].Index == it.AnswerArea!!.split("-")[0].toInt()) {
                    isFirst = true
                }
            }
        }
        return isFirst
    }

    /**
     * 根据index找出position
     */
    private fun getTextPosition(index: Int): Int {
        var position = -1
        textInfoList.forEachIndexed { i, textInfo ->
            if (textInfo.Index == index) {
                position = i
            }
        }
        return position
    }

    fun adjustFontSize() {
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(binding.tvLeader,15)
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(binding.tvIndex,15)
    }
}